<template>
  <div ref="wrapper_hook" class="wrapper"/>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'balanceBar',
  props: {
    source: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    source(newValue) {
      this._initECharts(newValue)
    }
  },
  mounted() {
    this._initECharts(this.source)
    window.addEventListener('resize', this.resize)
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', this.resize)
    })
  },
  destroyed() {
    this.chart.dispose()
  },
  methods: {
    _initECharts(data) {
      this.chart ? this.update(data) : this.draw(data)
    },
    resize(delay = 400) {
      setTimeout(() => {
        this.chart && this.chart.resize()
      }, delay)
    },
    draw(data) {
      this.chart = echarts.init(this.$refs.wrapper_hook)
      const options = {
        color:['#28DC32FF','#F9C14EFF','#28DEF6FF','#188df0','#F84ABFFF','#F53D1FFF'],
        tooltip: {
          trigger: 'item'
        },
        legend:{
          show:false,
          top: 'center',
          left:'center',
          // right: 20,
          icon:'circle',
          orient:'vertical',
          // formatter: params => this.getLegend(params)
        },
        toolbox: {
          show: true
        },
        grid: {
          top: 44,
          right: 24,
          bottom: 24
        },
        series: [
          {
            type: 'pie',
            radius: '60%',
            center:['50%','50%'],
            hoverAnimation: true,
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 2
            },
           label: {
             fontSize: '14',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
              }
            },
            labelLine: {
              show: true,
              length:16
            },
            data
          }
        ]
      }
      this.chart.setOption(options)
      this.chart.on('click', params => {
        this.$emit('change', params)
      })
    },
    update(data) {
      if (!this.chart) return
      const options = this.chart.getOption()
      options.series[0].data = data
      this.chart.setOption(options, true)
    }
  }
}
</script>

<style scoped>
.wrapper {
  width: 100%;
  min-height: 280px;
}
</style>

